<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .msg-area {
            width: 800px;
            height: 500px;
            overflow-y: scroll;
            border: 1px solid #aaa;
            background-color: #aaaaaa2e;
            padding-bottom: 25px;
        }

        .msg-area > span {
            display: inline-block;
            width: 100%;
            text-align: right;
            color: #666;
            font-size: 14px;
            font-family: "Arial Black";
        }

        .timeline {
            display: block;
        }

        .join {
            display: inline-block;
            width: 100%;
            color: #aaa;
            text-align: center;
            font-size: 12px;
            height: 25px;
            line-height: 25px;
            font-family: "Arial Black";
        }

        .myMsg {
            display: inline-block;
            margin-top: 15px;
            text-align: left;
            font-size: 18px;
            min-height: 30px;
            line-height: 25px;
            color: #4c4c4c;
        }

        .myMsg > span {
            display: inline-block;
            margin-left: 20px;
            position: relative;
        }

        .content {
            background-color: #FFFFFF;
            display: inline-block;
            padding: 5px 10px;
            border-radius: 10px;
            word-wrap: break-word;
            max-width: 300px;
        }

        .oMsg {
            display: block;
            margin-top: 15px;
            text-align: right;
        }

        .oMsg > span {
            display: inline-block;
            margin-right: 20px;
            position: relative;
        }

        .msgImage {
            max-width: 100px;
        }
    </style>
</head>

<body>
<div id="app">
    <div class="msg-area" id="area">
        <span>当前人数:{{num}}</span>
        <div v-for="msg in messages">

            <!-- 系统消息-->
            <div v-if="msg.msgType==1" class="join">
                {{msg.name}} 加入聊天室
            </div>
            <div v-if="msg.msgType==2" class="join">
                {{msg.name}} 退出聊天室
            </div>
            <div v-if="msg.msgType==0" class="myMsg">
                <span>{{msg.name}}</span>
                <div class="content">
                    <img class="msgImage" :src="msg.content" v-if="msg.contentType=='image'">
                    <span v-if="msg.contentType=='text'">{{msg.content}}</span>
                </div>
                <span class="timeline">{{msg.date}}</span>
            </div>
            <div v-if="msg.msgType==-1" class="oMsg">
                <div class="content">
                    <img class="msgImage" :src="msg.content" v-if="msg.contentType=='image'">
                    <span v-if="msg.contentType=='text'">{{msg.content}}</span>
                </div>
                <span class="timeline">{{msg.date}}</span>
                <span>我</span>
            </div>
        </div>
    </div>
    <div v-if="!show">
        <input type="text" name="name" v-model="token" id="name" placeholder="请输入姓名">
        <input type="button" value="确定" @click="start">
    </div>
    <div v-if="show">
        <textarea v-model="msg.content" style="margin-top: 25px;width: 800px;height: 150px;border: 1px solid #666"
                  @keyup.enter="sendTextMsg($event)"></textarea>
        <input type="file" @change="sendImageMsg" ref="image">
        <input type="button" value="确定" @click="sendTextMsg">

    </div>
</div>
</body>
<script src=" https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            ws: '',
            token: '',
            show: false,
            num: 0,
            messages: [],
            msg: {
                contentType: '',
                content: ''
            }
        },
        created() {
        },
        mounted() {
            this.token = localStorage.getItem('token');
            if (this.token) {
                this.start();
            }

        },
        methods: {
            send() {
                this.ws.send(JSON.stringify(this.msg));
            },
            sendImageMsg() {
                this.msg.contentType = 'image';
                let image = this.$refs.image.files[0];
                let reader = new FileReader();
                reader.readAsDataURL(image)
                reader.onload = (e) => {
                    this.msg.content = e.target.result;
                    this.send();
                }
            },
            sendTextMsg(event) {
                event.preventDefault();
                this.msg.contentType = 'text';
                this.send();
            },
            start() {
                let that = this;
                this.ws = new WebSocket("ws://127.0.0.1:8686/privateChat?token=e8996e1220bf79ed27235810137467f&toUid=5");
                //readyState属性返回实例对象的当前状态，共有四种。
                //CONNECTING：值为0，表示正在连接。
                //OPEN：值为1，表示连接成功，可以通信了。
                //CLOSING：值为2，表示连接正在关闭。
                //CLOSED：值为3，表示连接已经关闭，或者打开连接失败
                //例如：if (ws.readyState == WebSocket.CONNECTING) { }

                //【用于指定连接成功后的回调函数】
                this.ws.onopen = function (evt) {
                    console.log("Connection open ...");
                };
                //ws.addEventListener('open', function (event) {
                //    ws.send('Hello Server!');
                //};

                //【用于指定收到服务器数据后的回调函数】
                //【服务器数据有可能是文本，也有可能是二进制数据，需要判断】
                this.ws.onmessage = function (event) {
                    that.msg.content = ''
                    console.log("Received Message: " + event.data);
                    let data = JSON.parse(event.data);
                    if (data.msgType == 1 || data.msgType == 2) {
                        that.num = data.content
                    }
                    that.messages.push(data);
                    let div = document.getElementById('area');
                    console.log(div.scrollHeight)
                    div.scrollTop = div.scrollHeight + 300;
                };

                //[【于指定连接关闭后的回调函数。】
                this.ws.onclose = function (evt) {
                    console.log("Connection closed.");
                };

                //发送文本
                // //发送Blob数据
                // var file = document
                //     .querySelector('input[type="file"]')
                //     .files[0];
                // ws.send(file);
                // //发送ArrayBuffer
                // var img = canvas_context.getImageData(0, 0, 400, 320);
                // var binary = new Uint8Array(img.data.length);
                // for (var i = 0; i < img.data.length; i++) {
                //     binary[i] = img.data[i];
                // }
                // ws.send(binary.buffer);

                // //webSocket.bufferedAmount
                // //bufferedAmount属性，表示还有多少字节的二进制数据没有发送出去。它可以用来判断发送是否结束
                // var data = new ArrayBuffer(10000000);
                // socket.send(data);

                // if (socket.bufferedAmount === 0) {
                //     // 发送完毕
                // } else {
                //     // 发送还没结束
                // }

                //webSocket.onerror 用于指定报错时的回调函数

                this.ws.onerror = function (event) {
                };

                this.ws.addEventListener("error", function (event) {
                });
                this.show = true;
            }
        }
    })


</script>

</html>